import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

@WebServlet("/methodOne")
public class getParameter extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //  设置好响应格式，浏览器才知道是html文本
        resp.setContentType("text/html;charset=utf8");
        StringBuilder stringBuilder = new StringBuilder();

        //  获取请求报头中所有的 key 值 赋值给 queryStringKeys
        Enumeration<String> queryStringKeys = req.getParameterNames();
        //  但枚举容器里还有 key 值 时，循环继续
        while (queryStringKeys.hasMoreElements()){
            // 拿到下一个 key 值  赋值给 key
            String key = queryStringKeys.nextElement();
            //  将key 及其所对应的 value 放到stringBuilder容器中
            stringBuilder.append(key + ": " + req.getParameter(key));
            stringBuilder.append("<br>");
        }
        resp.getWriter().write(stringBuilder.toString());
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //  将POST请求的数据格式转换为 utf8
        req.setCharacterEncoding("utf8");

//        resp.setContentType("text/html; charset=utf8");
        //  前端通过body，以form表单的形式，将username password传递给服务器
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        if (username == null){
            System.out.println("不存在 username");
        }
        if (password == null){
            System.out.println("不存在 password");
        }
        resp.getWriter().write("ok");
        System.out.println("username =" + username + "; password =" + password);
    }
}
